// pages/event-report/index.js
import {curTime,curTime1,todayDay,todayMonth} from '../../third-utils/time/index.js';
Page({

    /**
     * 页面的初始数据
     */
    data: {
      showModal:false,
        curDate:'',
        curMonth:'',
        selectedDays:[],
        lockday:[],
        weekTitle:['日','一','二','三','四','五','六'],
        weekValue:[],
        curDay:1,
        eventList:[],
        curSelect:0,
        categroyListAll:[],
        categroyList:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            curDate:curTime1
        })
        this.getWeek(this.data.curDate)
        wx.request({
            url: 'https://babyplanet.isv-dev.youzan.com/api/recordType/findList',
            data: {
                level:1
            },
            method: 'post',
            success: (res) => {
              if (res.data.code == 200) {
                this.setData({
                    categroyList:res.data.data
                })
                let i={
                  id:'',
                  name:'全部记录'
                }
                this.data.categroyListAll=JSON.parse(JSON.stringify(res.data.data))
                this.data.categroyListAll.unshift(i)
                this.setData({
                  categroyListAll:this.data.categroyListAll
                })
                this.getData()
                this.getDateList(this.data.curDate)
              }
            }
          })
    },
    getDateList(val){
      let post={
        babyId:32,
        startDate:'',
        endDate:'',
        typeParentId:this.data.categroyListAll[this.data.curSelect].id
      }
      if(val){

        let attr=val.split('-')
        post.startDate=attr[0]+'-'+attr[1]+'-01'
        post.endDate=attr[0]+'-'+attr[1]+'-31'
      }
      wx.request({
        url: 'https://babyplanet.isv-dev.youzan.com/api/babyRecord/findDateByMonth',
        data: post,
        method: 'post',
        success: (res) => {
          if (res.data.code == 200) {
            this.setData({
              selectedDays:res.data.data
            })
            console.log(this.data.selectedDays,1222)
          }
        }
      })
    },
    weekSelect(e){

      let item = this.data.weekValue[e.currentTarget.dataset.index]
      if (item.checked) {
        return
      }
      let year = this.data.curDate.split('-')[0]
      this.setData({
        curDate: year + '-' + item.month + '-' + item.date
      })
      this.hideModal()
      this.getData()
  
      this.getWeek(this.data.curDate)

    },
    getMonth(e){
      this.setData({
        curMonth:e.detail.month
      })
      this.getDateList(e.detail.month)
    },
    getdate(e){
      this.setData({
        curDate:e.detail.datestr
      })
      this.hideModal()
      this.getData()
      
        this.getWeek(this.data.curDate)
    },
    toDetail(e){
      
      let idx=e.currentTarget.dataset.index
      let row=this.data.eventList[idx]

      let name=row.typeParentName || row.typeName
      
      let route=[
        {
          title:'消化道',
          path:'/pages/event-xhd/index?cateId='
        }, {
          title:'皮肤',
          path:'/pages/event-pf/index?cateId='
        }, {
          title:'呼吸道',
          path:'/pages/event-hxd/index?cateId='
        }, {
          title:'喂奶',
          path:'/pages/event-wn/index?cateId='
        },{
          title:'过敏原',
          path:'/pages/event-gmy/index?cateId='
        },{
          title:'医疗',
          path:'/pages/event-yl/index?cateId='
        },{
          title:'用药',
          path:'/pages/event-medication/index?cateId='
        },{
          title:'辅食',
          path:'/pages/event-fs/index?cateId='
        },
      ]
      route.some((item,index)=>{
        if(item.title==name){

          wx.navigateTo({
            url: item.path+this.data.categroyList[index].id+`&typeId=${row.typeId}&id=${row.id}`
          })
        }
      })
    },
    pickerChangeType(e){
      this.setData({
        curSelect:e.detail.value
      })
      this.getData()
      if(this.data.curMonth){
        this.getDateList(this.data.curMonth)

      }else{
        this.getDateList(this.data.curDate)

      }
      
    },
    showModal(){
      this.data.showModal=!this.data.showModal
      this.setData({
        showModal:this.data.showModal
      })
    },
    hideModal(){
      this.setData({
        showModal:false
      })
    },
    
    // 获取日历内容
    getWeek(dateData) {
      let selected = []
      let selectDays = []
      // 判断当前是 安卓还是ios ，传入不容的日期格式
      if (typeof dateData !== 'object') {
        dateData = dateData.replace(/-/g, "/")
      }
      let _date = new Date(dateData);
      let year = _date.getFullYear(); //年
      let month = _date.getMonth() + 1; //月
      let date = _date.getDate(); //日
      let day = _date.getDay(); // 天
      let canlender = [];
      
      let dates = {
        firstDay: new Date(year, month - 1, 1).getDay(),
        lastMonthDays: [], // 上个月末尾几天
        currentMonthDys: [], // 本月天数
        nextMonthDays: [], // 下个月开始几天
        endDay: new Date(year, month, 0).getDay(),
        weeks: []
      }
      // 循环上个月末尾几天添加到数组
      for (let i = dates.firstDay; i > 0; i--) {
        let dd = new Date(year, month-1, -(i-1));
        let checked = true;
        
        if(todayMonth > month - 1){
         
          checked=false
        }
        // selectDays.forEach(v => {
        //   let selDate = v.split('-');
        //   let ddstr = this.dateStr(dd);
        //   if (ddstr == v) {
        //     checked = true;
        //   }
        // })
        dates.lastMonthDays.push({
          'date': dd.getDate() + '',
          'month': month - 1,
          checked
        })
      }
      // 循环本月天数添加到数组
      for (let i = 1; i <= new Date(year, month, 0).getDate(); i++) {
        let have = false;
        let checked = false;
        let curDay = false;
        // for (let j = 0; j < selected.length; j++) {
        //   let selDate = selected[j].split('-');
        //   if (Number(year) === Number(selDate[0]) && Number(month) === Number(selDate[1]) && Number(i) === Number(selDate[2])) {
        //     have = true;
        //   }
        // }
        // if((todayDay>i && month<todayMonth) || (todayDay<i && month==todayMonth)){
        //   checked=true
        // }
        if(((todayMonth == month && i-todayDay > 0))){
         
          checked=true
        }
        // nowMonth > day.month || ((nowMonth >= day.month && day.date-nowDate <= 0))
        if(date==i){
          curDay=true
        }
        console.log(year, month,i,date,8888)
        selectDays.forEach(v => {
          let selDate = v.split('-');
          if (Number(year) === Number(selDate[0]) && Number(month) === Number(selDate[1]) && Number(i) === Number(selDate[2])) {
            checked = true;
          }
        })
        dates.currentMonthDys.push({
          'date': i + "",
          'month': month,
          curDay,
          // have,
          checked
        })
      }
      // 循环下个月开始几天 添加到数组
      for (let i = 1; i < 7 - dates.endDay; i++) {
        dates.nextMonthDays.push({
          'date': i + '',
          'month': month + 1
        })
      }

      canlender = canlender.concat(dates.lastMonthDays, dates.currentMonthDys, dates.nextMonthDays)
      // 拼接数组  上个月开始几天 + 本月天数+ 下个月开始几天
      for (let i = 0; i < canlender.length; i++) {
        if (i % 7 == 0) {
          dates.weeks[parseInt(i / 7)] = new Array(7);
        }
        dates.weeks[parseInt(i / 7)][i % 7] = canlender[i]
      }
      // 渲染数据
      dates.weeks.some(item=>{
        item.some(day=>{
          if(day.date==date && day.month==month){
            this.setData({
              weekValue:item
            })
          }
        })
      })
      console.log(this.data.weekValue)
    },
    handleCheck(e){
      console.log(e,12112)
      let idx=e.currentTarget.dataset.index
      let list=e.currentTarget.dataset.list
      wx.previewImage({
        current: list.split(',')[idx], // 当前显示图片的http链接
        urls: list.split(',') // 需要预览的图片http链接列表
      })
    },
    getEndDate(curDay){
      var today = new Date(curDay); // 获取当前日期和时间
      var tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000); // 获取明天的日期，通过增加一天的毫秒数来实现
      
      var year = tomorrow.getFullYear(); // 获取明天的年份
      var month = tomorrow.getMonth() + 1; // 获取明天的月份（注意月份是从 0 开始计数的，所以需要加 1）
      var date = tomorrow.getDate(); // 获取明天的日期
      let tomorrowDate = year + "-" + (month < 10 ? "0"+month:month) + "-" +  (date < 10 ? "0"+date:date)
      return tomorrowDate
    },
    getData(){
      wx.request({
        url: 'https://babyplanet.isv-dev.youzan.com/api/babyRecord/findList',
        data: {
          babyId:32,
          "startDate": this.data.curDate+' 00:00:00',
          "endDate": this.getEndDate(this.data.curDate)+' 00:00:00',
          typeParentId:this.data.categroyListAll[this.data.curSelect].id
        },
        method: 'post',
        success: (res) => {
          if (res.data.code == 200) {
            this.setData({
              eventList:res.data.data
            })
          }
        }
      })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },
    toAdd(e){
      let idx=e.currentTarget.dataset.index
      let route=[
        {
          title:'消化道',
          path:'/pages/event-xhd/index?cateId='
        }, {
          title:'皮肤',
          path:'/pages/event-pf/index?cateId='
        }, {
          title:'呼吸道',
          path:'/pages/event-hxd/index?cateId='
        }, {
          title:'医疗',
          path:'/pages/event-yl/index?cateId='
        },{
          title:'喂奶',
          path:'/pages/event-wn/index?cateId='
        },{
          title:'过敏原',
          path:'/pages/event-gmy/index?cateId='
        },{
          title:'辅食',
          path:'/pages/event-fs/index?cateId='
        },{
          title:'用药',
          path:'/pages/event-medication/index?cateId='
        },
      ]
      route.some(item=>{
        if(item.title==this.data.categroyList[idx].name){

          wx.navigateTo({
            url: item.path+this.data.categroyList[idx].id
          })
        }
      })
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
      wx.redirectTo({
        url: 'url',
      })
    }
})